//
//  ConnectWiFiViewController.m
//  GetPowerDBO
//
//  Created by 周博 on 2017/6/26.
//  Copyright © 2017年 BogoZhou. All rights reserved.
//

#import "ConnectWiFiViewController.h"
#import <SystemConfiguration/CaptiveNetwork.h>
#import "PickerViewController.h"
#import "WebViewController.h"

@interface ConnectWiFiViewController ()<UIScrollViewDelegate>
{
    
}
@property (nonatomic,strong) UIPageControl *pageControl;

@property (nonatomic,strong) NSString *macString;
@property (nonatomic,strong) NSString *verString;

@end

@implementation ConnectWiFiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self UISetting];
//    [self getWiFiNameFun];
    [self addNoticeForKeyboard];
    [self getNoti];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)getNoti{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chooseWifiNameByNoti:) name:@"wifiName" object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getWiFiNameFun) name:@"researchWifi" object:nil];
}

- (void)chooseWifiNameByNoti:(NSNotification *)noti{
    NSDictionary *dic = noti.object;
    _textFieldWiFiName.text = dic[@"name"];
    _textFieldWiFiPassword.text = [@"-" isEqualToString:dic[@"id"]] ? @"" : dic[@"id"];
}


- (void)UISetting{
    _buttonSuccess.layer.masksToBounds = YES;
    _buttonSuccess.layer.cornerRadius = 5;
    
    NSArray * picArray = @[@"bangzhu1",@"bangzhu2"];
    
    self.backScrollView.contentSize = CGSizeMake(kScreenSize.width * picArray.count,_backScrollView.sizeHeight);
    //设置 分成不同页面
    self.backScrollView.pagingEnabled = YES;
    //代理
    self.backScrollView.delegate = self;
    //设置是否可以左右滑动
    self.backScrollView.showsHorizontalScrollIndicator = NO;
    self.backScrollView.showsVerticalScrollIndicator = NO;
    //设置反弹动画
    self.backScrollView.bounces = NO;
    //背景颜色
    self.backScrollView.backgroundColor = [UIColor whiteColor];
    //是否 可翻页
    self.backScrollView.delaysContentTouches = YES;
    //触摸事件
    self.backScrollView.canCancelContentTouches = NO;
    //用户交互
    self.backScrollView.userInteractionEnabled = YES;
    
    for (NSInteger i = 0; i < picArray.count; i ++) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenSize.width * i , 0, kScreenSize.width, _backScrollView.sizeHeight)];
        
        imageView.image = [UIImage imageNamed:picArray[i]];
        
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        
        [self.backScrollView addSubview:imageView];
    }
    
    //创建UIPageControl
    _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, _backScrollView.allHeight - 30, kScreenSize.width, 30)];  //创建UIPageControl，位置在屏幕最下方。
    _pageControl.userInteractionEnabled = YES;

    _pageControl.pageIndicatorTintColor = kd6d6d6;
    _pageControl.currentPageIndicatorTintColor = kGreenColor;
    _pageControl.numberOfPages = picArray.count;//总的图片页数
    _pageControl.currentPage = 0; //当前页
    [_pageControl addTarget:self action:@selector(pageTurn:) forControlEvents:UIControlEventValueChanged];  //用户点击UIPageControl的响应函数
    [self.view addSubview:_pageControl];
}

//然后是点击UIPageControl时的响应函数pageTurn
- (void)pageTurn:(UIPageControl*)sender
{
    //令UIScrollView做出相应的滑动显示
    CGSize viewSize = _backScrollView.frame.size;
    CGRect rect = CGRectMake(sender.currentPage * viewSize.width, 0, viewSize.width, viewSize.height);
    [_backScrollView scrollRectToVisible:rect animated:YES];
}

//其次是UIScrollViewDelegate的scrollViewDidEndDecelerating函数，用户滑动页面停下后调用该函数。

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    //更新UIPageControl的当前页
    CGPoint offset = scrollView.contentOffset;
    CGRect bounds = scrollView.frame;
    [_pageControl setCurrentPage:offset.x / bounds.size.width];
    NSLog(@"%f",offset.x / bounds.size.width);
}

#pragma mark - 点击事件

//前往网页配置
- (IBAction)goWebViewButtonClick:(UIButton *)sender {
    UIStoryboard *storyboard = kMainStroyboard;
    WebViewController *webView = [storyboard instantiateViewControllerWithIdentifier:@"WebViewController"];
    webView.titleString = @"网页配置WiFi";
    webView.urlString = @"http://192.168.4.1/wifi_set.html";
    [self.navigationController pushViewController:webView animated:YES];
}

//帮助
- (IBAction)helpButtonClick:(UIButton *)sender {
}




- (IBAction)backButtonClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

//点击选择wifi
- (IBAction)chooseWifiList:(UIButton *)sender {
    NSString *wifiName = [[NSUserDefaults standardUserDefaults] valueForKey:@"wifi"];
    NSArray *wifiArray = [wifiName componentsSeparatedByString:@",,"];
    if (wifiArray.count > 0) {
        UIStoryboard *storyboard = kMainStroyboard;
        PickerViewController *pickerView = [storyboard instantiateViewControllerWithIdentifier:@"PickerViewController"];
        
        pickerView.dataArray = wifiArray;
        pickerView.type = @"3";
        pickerView.modalPresentationStyle = UIModalPresentationOverFullScreen;
        [self presentViewController:pickerView animated:YES completion:nil];
    }else{
        kAlert(@"缺少WiFi列表");
    }
    
}


- (IBAction)successButtonClick:(UIButton *)sender {
//    kAlert(@"点击连接WiFi");
//    NSString *wifiType = [[NSUserDefaults standardUserDefaults] valueForKey:@"net"];
    
    if ([_labelWiFiName.text rangeOfString:@"ChongDianDian"].location ==NSNotFound) {
        kAlert(@"请连接充电宝热点");
        return;
    }
    
    if ([BGFunctionHelper isNULLOfString:_textFieldWiFiName.text]) {
        kAlert(@"请输入要连接的WiFi名");
        return;
    }
    
    

    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"提交后请耐心等待" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    UIAlertAction *sureAction  = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSString *wifiName = [[NSUserDefaults standardUserDefaults] valueForKey:@"wifi"];
        NSArray *wifiArray = [wifiName componentsSeparatedByString:@",,"];
        NSMutableArray *array = [NSMutableArray array];
        if (wifiArray.count > 0) {
            for (NSInteger i = 0; i < wifiArray.count; i ++) {
                NSString *nameString = wifiArray[i];
                if([nameString rangeOfString:_textFieldWiFiName.text].location !=NSNotFound)//_roaldSearchText
                {
                    NSLog(@"yes");
                    
                    nameString = [NSString stringWithFormat:@"%@|-+%@",_textFieldWiFiName.text,_textFieldWiFiPassword.text.length > 0 ? _textFieldWiFiPassword.text : @"-"];
                    [array addObject:nameString];
                }else{
                    [array addObject:nameString];
                }
            }
            wifiName = [array componentsJoinedByString:@",,"];
            [[NSUserDefaults standardUserDefaults] setValue:wifiName forKey:@"wifi"];
        }
        [self getMacInfo];
    }];
    
    [alertController addAction:cancelAction];
    [alertController addAction:sureAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
    
}

- (void)wifiSettingFunByCode{
    [self.hub hideAnimated:YES];
    
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"正在配置...", @"HUD loading title");
    [[AFClient shareInstance] postUPdateWiFiInfoByStaN:_textFieldWiFiName.text staP:_textFieldWiFiPassword.text mac:_macString ver:_verString ProgressBlock:nil success:^(id responseBody) {
        [self.hub hideAnimated:YES];
        NSLog(@"%@",responseBody);
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
        //WiFi配置信息已发出，设备正在重启
        [self alertVCByTitle:@"WiFi配置信息已发出，设备正在重启\n请注意充电宝指示灯变化"];
    }];
}

- (void)getMacInfo{
    [self.hub hideAnimated:YES];
    
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"正在获取充电宝信息...", @"HUD loading title");
    [[AFClient shareInstance] getMacInfoProgressBlock:nil success:^(id responseBody) {
        [self.hub hideAnimated:YES];
        NSLog(@"getMacInfo -> %@",responseBody);
        NSString *responseBodyString = responseBody;
        NSString *responseBodyString2 = responseBody;
        
        NSArray *array = [responseBodyString componentsSeparatedByString:@"'mac':'"];
        NSString *macInfoA = array.lastObject;
        _macString = [macInfoA substringToIndex:12];
        
        NSLog(@"macString - > %@",_macString);
        
        NSArray *array2= [responseBodyString2 componentsSeparatedByString:@"'ver':'"];
        NSString *verInfoA = array2.lastObject;
        NSArray *array3 = [verInfoA componentsSeparatedByString:@"'}"];
        _verString = array3.firstObject;
        
        NSLog(@"verString -> %@",_verString);
        
        [self wifiSettingFunByCode];
        
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
    }];
}

////获取当前WiFi名称
//- (void)getWiFiNameFun{
//    id info = nil;
//    NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
//    for (NSString *ifnam in ifs) {
//        info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
//        NSString *str = info[@"SSID"];
////        NSString *str2 = info[@"BSSID"];
////        NSString *str3 = [[ NSString alloc] initWithData:info[@"SSIDDATA"] encoding:NSUTF8StringEncoding];
//        
//        
//        _labelWiFiName.text = [NSString stringWithFormat:@"当前连接WiFi：%@",[BGFunctionHelper isNULLOfString:str] ? @"未连接" : str];
//    }
//}

#pragma mark - 键盘通知
- (void)addNoticeForKeyboard {
    
    //注册键盘出现的通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification object:nil];
    //注册键盘消失的通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification object:nil];
}

///键盘显示事件
- (void) keyboardWillShow:(NSNotification *)notification {
    //获取键盘高度，在不同设备上，以及中英文下是不同的
    CGFloat kbHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    
    //计算出键盘顶端到inputTextView panel底端的距离(加上自定义的缓冲距离INTERVAL_KEYBOARD)
    CGFloat offset = (_deepView.orginY - _textFieldWiFiPassword.allHeight + kbHeight) - (self.view.frame.size.height - kbHeight);
    
    // 取得键盘的动画时间，这样可以在视图上移的时候更连贯
    double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    //将视图上移计算好的偏移
    if(offset > 0) {
        [UIView animateWithDuration:duration animations:^{
            self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
        }];
    }
}

///键盘消失事件
- (void) keyboardWillHide:(NSNotification *)notify {
    // 键盘动画时间
    double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    //视图下沉恢复原状
    [UIView animateWithDuration:duration animations:^{
        self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    }];
}

- (void)alertVCByTitle:(NSString *)title{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
